/*
 * Code Generated with ChatGPT
 */
using UnityEngine;

public class CameraBehavior : MonoBehaviour
{
    public float moveSpeed = 5f;
    public float lookSpeed = 2f;

    private float rotationX = 0f;
    private float rotationY = 0f;
    private bool isDragging = false;
    private Vector3 lastMousePosition;

    private void Start()
    {
        // Initialize camera rotation based on the current transform rotation
        rotationX = transform.eulerAngles.x;
        rotationY = transform.eulerAngles.y;
    }

    private void Update()
    {
        HandleMouseInput();
        HandleKeyboardInput();
        UpdateCameraRotation();
    }

    private void HandleMouseInput()
    {
        if (Input.GetMouseButtonDown(0))
        {
            isDragging = true;
            lastMousePosition = Input.mousePosition;
        }
        else if (Input.GetMouseButtonUp(0))
        {
            isDragging = false;
        }
    }

    private void HandleKeyboardInput()
    {
        float horizontalInput = Input.GetAxis("Horizontal");
        float verticalInput = Input.GetAxis("Vertical");
        float verticalMovement = 0f;

        if (Input.GetKey(KeyCode.Q))
        {
            verticalMovement = -1f;
        }
        else if (Input.GetKey(KeyCode.E))
        {
            verticalMovement = 1f;
        }

        Vector3 moveDirection = new Vector3(horizontalInput, verticalMovement, verticalInput);
        transform.Translate(moveDirection * moveSpeed * Time.deltaTime);
    }

    private void UpdateCameraRotation()
    {
        if (isDragging)
        {
            Vector3 currentMousePosition = Input.mousePosition;
            Vector3 mouseDelta = currentMousePosition - lastMousePosition;

            rotationX -= mouseDelta.y * lookSpeed;
            rotationX = Mathf.Clamp(rotationX, -90f, 90f);

            rotationY += mouseDelta.x * lookSpeed;

            transform.rotation = Quaternion.Euler(rotationX, rotationY, 0f);

            lastMousePosition = currentMousePosition;
        }
    }
}
